package com.qdsg.ysg.doctor.ui.activity.mine;

import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseLoginActivity;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.ui.LoginActivity;
import com.qdsg.ysg.doctor.ui.MainActivity;
import com.qdsg.ysg.doctor.ui.dialog.RulesDialogFragment;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.constant.JDConstant;
import com.rest.response.LoginResponse;
import com.tencent.wework.api.IWWAPI;
import com.tencent.wework.api.WWAPIFactory;
import com.tencent.wework.api.model.WWAuthMessage;

import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.PreferencesHelper;

/**
 * @Description: 忘记密码
 * @Author: lzp
 * @CreateDate: 2022/7/01 15:31
 * @UpdateRemark: 更新说明
 */
public class WxLoginActivity extends BaseLoginActivity {
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;

    private ProgressDialog mDialog;
    private static final String SCHEMA = JDConstant.isTest ? "wwauth24066edfdce8e105000008" : "wwauthfa243843dbc39f5c000017";
    IWWAPI iwwapi;


    @Override
    protected int getLayoutResource() {
        return R.layout.aty_wx_login;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initData() {
        iwwapi = WWAPIFactory.createWWAPI(this);
        iwwapi.registerApp(SCHEMA);
        if (PreferencesHelper.getInstance().getBoolean(this, "isAgree")) {
            cbAgree.setChecked(true);
        } else {
            cbAgree.setChecked(false);
        }
    }

    @OnClick({R.id.btn_wx_login, R.id.tv_agree, R.id.btn_to_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_wx_login:
                if (!cbAgree.isChecked()) {
                    ToastUtil.showToastCenter(mContext, "请先阅读并同意法律声明及隐私权政策");
                    return;
                }

                final WWAuthMessage.Req req = new WWAuthMessage.Req();
                if (JDConstant.isTest) {
                    //测试
                    req.sch = "wwauth24066edfdce8e105000008";
                    req.appId = "ww24066edfdce8e105";
                    req.agentId = "1000008";
                } else {
                    //正式
                    req.sch = "wwauthfa243843dbc39f5c000017";
                    req.appId = "wxfa243843dbc39f5c";
                    req.agentId = "1000017";
                }
                req.state = UUID.randomUUID().toString();

                iwwapi.sendMessage(req, resp -> {
                    if (resp instanceof WWAuthMessage.Resp) {
                        WWAuthMessage.Resp rsp = (WWAuthMessage.Resp) resp;
                        if (rsp.errCode == WWAuthMessage.ERR_CANCEL) {
                            ToastUtil.showToast(mContext, "登录取消");
                        } else if (rsp.errCode == WWAuthMessage.ERR_FAIL) {
                            ToastUtil.showToast(mContext, "登录失败");
                        } else if (rsp.errCode == WWAuthMessage.ERR_OK) {
                            wxLogin(rsp.code);
                        }
                    }
                });
                break;
            case R.id.tv_agree:
                showRulesDialogFragment();
                break;
            case R.id.btn_to_login:
                startActivity(new Intent(mContext, LoginActivity.class));
                break;
            default:
                break;
        }
    }

    private void wxLogin(String code) {
        showLoginDialog(getString(R.string.logining_msg));
        RestProxy.getInstance().wxLogin(code, new Observer<LoginResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(LoginResponse loginResponse) {
                dismissLoginDialog();
                checkServiceRunning(mContext);
                BaseApplication.currentUserId = loginResponse.data.userId;
                BaseApplication.name = loginResponse.data.name;
                BaseApplication.jobTitle = loginResponse.data.jobTitle;
                BaseApplication.avatar = loginResponse.data.avatar;
                BaseApplication.sex = loginResponse.data.sex;
                BaseApplication.isAudit = loginResponse.data.isAudit;
                BaseApplication.xyAccount = loginResponse.data.videoAccountDTO.account;
                BaseApplication.xyPassword = loginResponse.data.videoAccountDTO.password;
                PreferencesHelper.getInstance().set(mContext, "token", loginResponse.data.token);
                PreferencesHelper.getInstance().set(mContext, "xyAccount", loginResponse.data.videoAccountDTO.account);
                PreferencesHelper.getInstance().set(mContext, "xyPassword", loginResponse.data.videoAccountDTO.password);
                PreferencesHelper.getInstance().set(mContext, "isAgree", cbAgree.isChecked());
                BaseApplication.userType = loginResponse.data.hosType;
                RestClient.getInstance().token = loginResponse.data.token;
                startActivity(MainActivity.class);
                WxLoginActivity.this.finish();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoginDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private RulesDialogFragment mRulesDialogFragment;

    private void showRulesDialogFragment() {
        mRulesDialogFragment = RulesDialogFragment.newInstance("7");
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }


    public void showLoginDialog(String msg) {
        if (null == mDialog) {
            mDialog = new ProgressDialog(this);
        }
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setTitle(msg);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.show();
    }

    public void dismissLoginDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        stopService(new Intent(mContext, WebSocketService.class));
    }
}
